#!/usr/bin/perl -w
use strict;
use warnings;
use Net::SNMP;
use Storable qw(retrieve);
use threads;
use threads::shared;
use FileHandle;
use OIDS;
use Cwd;

my $cur_dir = getcwd();
require "$cur_dir/common_snmp.pl";


my ($client_list, @threads, $ERR, $WARN, $timestamp);
my $duration = 10;
my $data_path = $cur_dir;
$data_path =~ s/cgi-bin/wMOS/;
# retrieve the %client_list
if (@ARGV >= 1) {
	$timestamp = $ARGV[0];
	$client_list = retrieve($timestamp);
	if(unlink($timestamp) != 1){
		print "Warning: File was not deleted.";
		$WARN .= "Warning: File was not deleted.";
	}
} else {
	print "ERROR: no argument passed";
	$ERR .= "ERROR: no argument passed\n";
	exit 1;
}

# host info
my $ip = '11.37.200.5';
my $host = '10.89.234.220';
my $community = 'Altest';

# create SNMP session 
my ($error, $session) = snmp_connect($host, $community);

foreach my $node (keys %$client_list){
	my $fh = FileHandle->new();
	my $t = threads->new(\&get_sessionstats, $session, $node, $fh, $client_list, $timestamp, $data_path);
	$t->join();
	push(@threads,$t);
}

#foreach (@threads) {
#        my $num = $_->join;
#        print "done with $num\n";
#}

$session->close();



sub get_sessionstats {
	my ($session, $node, $fh, $client_list, $timestamp, $data_path) = @_;
	my $client_mac = $client_list->{$node}->{'mac_hex'};
	my $AP_mac_hex = $client_list->{$node}->{'AP_hex'};
	my $APSlotId = $client_list->{$node}->{'APSlotId'};
	my $filename = $data_path . "/" . $client_mac . "-" . $timestamp . ".csv";
	$filename =~ s/:/-/g;
	my $client_mac_dec = mac_hex_decimal($client_mac);
	my $AP_mac_dec = mac_hex_decimal($AP_mac_hex);
	my $client_channel = $client_list->{$node}->{'channel'};
	my @interested_oid = ();	
		
	if (! -e $filename){
		open($fh, "> $filename");
		print $fh "timestamp,";
		foreach my $key (sort keys %interested_oid){
			foreach my $oid (sort keys %{$interested_oid{$key}}){
				print $fh "$oid,";
				my $oid_num = $interested_oid{$key}->{$oid};
				$oid_num =~ s/AP_mac_dec/$AP_mac_dec/e; # get oid for AP mac address
				$oid_num =~ s/APSlotId/$APSlotId/e; # get oid for AP Slot Id
				$oid_num =~ s/client_mac_dec/$client_mac_dec/e; # get oid for client mac
				$oid_num =~ s/client_channel/$client_channel/e; # get oid for client channel
				push(@interested_oid, $oid_num);
			}	
		}	
		print $fh "\n";	
	} else {
		open($fh, ">> $filename");
	}
	
	
	for(my $n = 0; $n<$duration; $n++){
		my $start = time();
		my $stationstats = $session->get_request(-varbindlist => \@interested_oid);
		print $fh time . ",";
		foreach my $key (@interested_oid){
			print $fh $stationstats->{"$key"} . ",";
		}

		print $fh "\n";
		while ((time - $start) lt 5) {}
	}
	close $fh;
}
